<!-- src/views/login.vue -->
<script setup lang="ts">
import { ref, reactive } from 'vue'
import axios from '../utils/axios'
import router from '../router/index.ts'

// 登录表单数据
interface LoginForm {
  mobile: string
  pwd: string
}

// 表单验证规则
const rules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur' }
  ]
}

// 表单数据
const form = reactive<LoginForm>({
  mobile: '',
  pwd: ''
})

// 加载状态
const loading = ref(false)

// 表单验证
const validateForm = () => {
  return new Promise((resolve, reject) => {
    // 这里可以添加表单验证逻辑
    if (!form.mobile || !form.pwd) {
      reject(new Error('请填写完整信息'))
    } else {
      resolve(true)
    }
  })
}

// 登录方法
const handleLogin = async () => {
  try {
    await validateForm()
    loading.value = true

    const response = await axios.post('/api/login', {
      mobile: form.mobile,
      pwd: form.pwd
    })

    console.log('登录响应:', response)

    if (response.data.code === 200) {
      // 登录成功，保存token
      // 根据你的描述，token在msg字段中
      let token = response.data.data?.token || response.data.msg;

      // 如果token仍然为空，尝试从其他可能的字段获取
      if (!token) {
        token = response.data.token || response.data.data;
      }

      console.log('获取到的token:', token)

      if (token) {
        sessionStorage.setItem('token', token)
        // 跳转到用户原本想访问的页面或首页
        const redirect = router.currentRoute.value.query.redirect as string || '/home'
        router.push(redirect)
      } else {
        // 添加更详细的调试信息
        console.log('完整响应数据:', response.data);
        // 尝试从更多可能的位置获取token
        let debugToken = response.data.data?.token ||
                        response.data.msg ||
                        response.data.token ||
                        response.data.data ||
                        response.data.accessToken ||
                        response.data.access_token;

        if (debugToken) {
          console.log('从其他字段获取到的token:', debugToken);
          sessionStorage.setItem('token', debugToken);
          const redirect = router.currentRoute.value.query.redirect as string || '/home';
          router.push(redirect);
        } else {
          alert('登录成功但未获取到token，请联系管理员');
        }
      }
    } else {
      alert(response.data.msg)
    }
  } catch (error) {
    console.error('登录失败:', error)
    alert('登录失败，请检查网络或联系管理员')
  } finally {
    loading.value = false
  }
}

// 忘记密码方法（预留接口）
const forgotPassword = () => {
  alert('忘记密码功能待实现')
}

// 清空表单
const resetForm = () => {
  form.mobile = ''
  form.pwd = ''
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo">
        <h1>系统登录</h1>
      </div>

      <div class="form-wrapper">
        <el-form :model="form" :rules="rules" label-width="80px">
          <el-form-item label="手机号" prop="mobile">
            <el-input
                v-model="form.mobile"
                placeholder="请输入手机号"
                clearable
                @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item label="密码" prop="pwd">
            <el-input
                v-model="form.pwd"
                type="password"
                placeholder="请输入密码"
                clearable
                @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                @click="handleLogin"
                :loading="loading"
                style="width: 100%"
            >
              登录
            </el-button>
          </el-form-item>

          <el-form-item>
            <div class="actions">
              <el-link type="primary" @click="resetForm">重置</el-link>
              <el-link type="primary" @click="forgotPassword">忘记密码？</el-link>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div class="footer">
        <p>© 2023 系统名称. 保留所有权利.</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  transition: all 0.3s ease;
}

.login-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.3);
}

.logo {
  text-align: center;
  padding: 30px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.logo h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
  font-weight: 600;
}

.form-wrapper {
  padding: 30px;
}

.actions {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.actions .el-link {
  margin: 0 10px;
}

.footer {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 12px;
  background: #f8f9fa;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    margin: 20px;
  }

  .logo h1 {
    font-size: 20px;
  }
}
</style>
